package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.pojo.Activity;
import com.gaohe.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

@Slf4j
@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam("page") Integer page,
                  @RequestParam("pageSize") Integer pageSize,
                  @RequestParam(value = "name", required = false) String name) {
        Page<Activity> activityPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Activity> qw = new LambdaQueryWrapper<>();
        qw.like(ObjectUtils.isNotEmpty(name), Activity::getActivityName, name);
        activityService.page(activityPage, qw);
        return R.success(activityPage);
    }


    /**
     * 新增
     *
     * @param activity
     * @return
     */
    @PostMapping
    public R add(@RequestBody Activity activity) {
        //设置活动开始时间  当前时间
        activity.setStartTime(LocalDate.now());
        boolean save = activityService.save(activity);
        return save ? R.success("新增成功") : R.error("新增失败");
    }

    /**
     * 根据 id 查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id) {
        return R.success(activityService.getById(id));
    }

    /**
     * 修改
     *
     * @param activity
     * @return
     */
    @PutMapping
    public R updateById(@RequestBody Activity activity) {
        return activityService.updateById(activity) ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 根据 id 删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteById(@RequestParam Long id) {
        return activityService.removeById(id) ? R.success("删除成功") : R.error("删除失败");
    }

    /*------------------小程序端----------------*/
    @GetMapping("/getActivityList")
    public R getActivityList(){
        return R.success(activityService.list());
    }
}
